const { app, BrowserWindow, ipcMain } = require('electron');
const { spawn } = require('child_process');
const path = require('path');
const { Worker } = require('worker_threads');


// app.disableHardwareAcceleration();

let mainWindow;

function createWindow() {
    mainWindow = new BrowserWindow({
        width: 2400,
        height: 1200,
        webPreferences: {
            nodeIntegration: true,
            contextIsolation: false,
        },
    });

    const startUrl = app.isPackaged
        ? `file://${path.join(process.resourcesPath, 'index.html')}`
        : `file://${path.join(__dirname, 'index.html')}`;

    mainWindow.loadURL(startUrl);
    mainWindow.webContents.openDevTools();
}

app.whenReady().then(() => {
    createWindow();

    const scriptPath = app.isPackaged
        ? path.join(process.resourcesPath, 'random_number_generator.py')
        : path.join(__dirname, 'random_number_generator.py');

    const pythonProcess = spawn('python3', [scriptPath]);

    pythonProcess.stdout.on('data', (data) => {
        const randomNumber = parseInt(data.toString().trim(), 10);
        mainWindow.webContents.send('random-number', randomNumber);
    });

    pythonProcess.stderr.on('data', (data) => {
        console.error(`Python script error: ${data}`);
    });

    pythonProcess.on('close', (code) => {
        console.log(`Python script exited with code ${code}`);
    });
});

app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit();
    }
});

app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
        createWindow();
    }
});

// const workerCount = 6;
// let workers = [];
// for (let i = 0; i < workerCount; i++) {
//     const worker = new Worker(path.join(__dirname, 'worker.js'), {
//         workerData: { index: i }
//     });

//     worker.on('message', (data) => {
//         mainWindow.webContents.send('render-frame', data);
//     });

//     workers.push(worker);
// }
